import CryptoJS from 'crypto-js'
export default {
    name: "Login",
    data() {
        var checkName = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请输入用户名"));
            }
            setTimeout(() => {
                var regName = /^[\u0391-\uFFE5\w]+$/;
                if (!regName.test(value)) {
                    callback(new Error("用户名由中文、英文或下划线组成"));
                }
                callback();
            }, 500);
        }
        var checkPass = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请输入密码"));
            }
            setTimeout(() => {
                var regPass = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/;
                if (!regPass.test(value)) {
                    callback(new Error("密码由英文和数字组合,6-10位"));
                }
                callback();
            }, 500);
        };
        var checkvalidNum = (rule, value, callback) => {
            console.log("验证码", value);
            if (!value) {
                callback(new Error("请输入验证码"));
            }
            setTimeout(() => {
                // if (value.replace(/[ ]/g, "") == "" || value.replace(/[ ]/g, "").length == 0) {
                //     console.log(value.replace(/[ ]/g, ""))
                //     callback(new Error("必须输入验证码"));
                // }
                callback();
            }, 500)
        }
        return {
            loginInfo: {
                name: '',
                pass: '',
                validNum: ''
            },
            validcodeUrl:'',
            HjseUrl:'/AIProjectApi',
            checked: true,
            rules: {
                name: [{
                    validator: checkName,
                    trigger: 'blur'
                }],
                pass: [{
                    validator: checkPass,
                    trigger: 'blur'
                }],
                validNum: [{
                    validator: checkvalidNum,
                    trigger: 'blur'
                }]
            }
        };
    },
    computed: {},
    watch: {
        //监听路由的去向
        '$route'(to, form) {
            console.log(to);
        }
    },
    created() {
        this.validcodeUrl = '';
        if (window.localStorage.getItem('checked') == "true") {
            this.getCookie();
        }
    },
    mounted() {
        this.validcodeUrl = this.HjseUrl +'/loginProductController/captcha.action?timestamp='+Math.random();
    },
    methods: {
        sbLogin(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //服务
                    var postData = {
                        username: this.loginInfo.name,
                        password: this.loginInfo.pass,
                        validNum: this.loginInfo.validNum
                    }
                    this.$http.post('/loginProductController/login', this.qs.stringify(postData))
                        .then((res) => {
                            if (res.status == 200) {
                                this.$message({
                                    message: '登录成功',
                                    type: 'success',
                                    duration: 800
                                });
                                window.localStorage.setItem("checked", this.checked);
                                window.localStorage.setItem('token', res.token)
                                window.localStorage.setItem('userInfo', JSON.stringify(res.user));
                                window.localStorage.setItem('isLogin', true);
                                //触发setIsLogin方法改变vuex中的isLogin的值
                                this.$store.commit('setIsLogin', true);
                                this.$router.push('/index');
                                if (this.checked == true) {
                                    //传入账号、密码、保存天数
                                    this.setCookie(this.loginInfo.name, this.loginInfo.pass, 7);
                                } else {
                                    //清空Cookie
                                    this.clearCookie();
                                }
                            } else {
                                this.$message.error(res.message);
                            }
                        })
                        .catch((res) => {
                            console.log(res)
                    })
                } else {
                    this.$message.error('输入格式不正确')
                }
            })
        },
        //设置cookie方法
        setCookie(name, pass, days) {
            var text = CryptoJS.AES.encrypt(pass, "secret key 123").toString(); //使用CryptoJS方法加密
            var saveDays = new Date(); //获取时间
            saveDays.setTime(saveDays.getTime() + 24 * 60 * 60 * 1000 * days); //保存的天数
            //字符串拼接存入cookie
            document.cookie =
                "name" + "=" + name + ";path=/;expires=" + saveDays.toGMTString();
            document.cookie =
                "pass" + "=" + text + ";path=/;expires=" + saveDays.toGMTString();
        },
        //读取cookie值
        getCookie() {
            if (document.cookie.length > 0) {
                var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下   多个空格
                for (var i = 0; i < arr.length; i++) {
                    var arr2 = arr[i].split("="); //再次切割
                    //这里会切割出以name为第0项的数组、以pass为第0项的数组，判断查找相对应的值
                    if (arr2[0] == "name") {
                        this.loginInfo.name = arr2[1]; //拿到账号
                    } else if (arr2[0] == "pass") {
                        // 拿到拿到加密后的密码arr2[1]并解密
                        var bytes = CryptoJS.AES.decrypt(
                            arr2[1].toString(),
                            "secret key 123"
                        );
                        var plaintext = bytes.toString(CryptoJS.enc.Utf8); //拿到解密后的密码（登录时输入的密码）
                        this.loginInfo.pass = plaintext;
                    }
                }
            }
        },
        //清除cookie
        clearCookie() {
            this.setCookie("", "", 0); //账号密码置空，天数置0
        }
    }
};